// @created: caoshi
// @date: 2021-06-13 19:41
// 系统优化相关操作的处理器
package handler

import (
	"academic/global"
	"academic/middleware"
	"academic/model/entity"
	"academic/model/request"
	"academic/model/response"
	"academic/service"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/satori/go.uuid"
	"net/http"
	"time"
)

const SessionId = "SESSION_ID"

func Captcha(c *gin.Context) {
	captchaId, b64s, _ := GenerateCaptcha(StringType)
	//fmt.Println("生成的验证码 ", b64s)
	// 获取session, 并存储生成的验证码Id
	session := sessions.Default(c)
	session.Set(SessionId, captchaId)
	_ = session.Save()
	c.String(http.StatusOK, b64s)
}

func Login(c *gin.Context) {
	var login request.Login
	err := c.ShouldBindJSON(&login)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
	}
	// 校验验证码
	session := sessions.Default(c)
	captchaId := fmt.Sprintf("%v", session.Get(SessionId))
	pass := VerifyCaptcha(captchaId, login.Captcha)
	if pass {
		if user, err := service.Login(&login); err != nil {
			response.FailWithMessage("用户名或密码错误", c)
		} else {
			tokenNext(c, *user)
		}

	} else {
		response.FailWithMessage("验证码错误", c)
	}

	//user, err := dao.FindByUsernameAndPwd(login.Username, login.Password)

}

/**
登录后签发token
*/
func tokenNext(c *gin.Context, user entity.SysUser) {
	j := &middleware.JWT{StringKey: []byte(global.GvaConfig.JWT.StringKey)}
	claims := request.CustomClaims{
		UUID:     uuid.UUID{},
		ID:       user.Id,
		Username: user.Username,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + global.GvaConfig.JWT.ExpiresTime,
			Issuer:    "nanshannan",
			NotBefore: time.Now().Unix() - 1000, // 签名生效时间
		},
	}

}

func Register(c *gin.Context) {
	fmt.Println("注册用户")
}
